package com.sjs.boot.dynamic.util;

import cn.hutool.core.util.StrUtil;
import com.sjs.boot.dynamic.http.exception.PlatformException;
import com.sjs.boot.dynamic.protocol.RetCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.MissingResourceException;

/**
 * @author uto_dev_008
 * @desc
 * @since 2021/11/26 11:20
 * Copyright (c) 2021 南京友拓信息技术有限公司 All rights reserved
 */
@Component
public class PropertiesUtil {
    private static final Logger LOG = LoggerFactory.getLogger(PropertiesUtil.class);
    private static Environment env;

    @Autowired
    protected void set(Environment env) throws IOException {
        PropertiesUtil.env = env;
    }

    /**
     * Get a value based on key , if key does not exist , null is returned
     *
     * @param key
     * @return
     */
    public static String getString(String key) {
        try {
            String value = env.getProperty(key);
            if (StrUtil.isEmpty(value)) {
                throw new PlatformException(key, RetCode.RESOURSE_MISS_ERROR.getCode());
            }
            return value;
        } catch (MissingResourceException e) {
            throw new PlatformException(e.getCause().getMessage(), RetCode.RESOURSE_MISS_ERROR.getCode());
        }
    }

    /**
     * Get a value based on key , if key does not exist , null is returned
     *
     * @param key
     * @return
     */
    public static String getString(String key, String defaultValue) {
        try {
            String value = env.getProperty(key);
            if (value == null) {
                return defaultValue;
            }
            return value;
        } catch (MissingResourceException e) {
            return defaultValue;
        }
    }

    /**
     * 根据key获取值
     *
     * @param key
     * @return
     */
    public static int getInt(String key) {
        String value = getString(key);
        return Integer.parseInt(value);
    }

    /**
     * 根据key获取值
     *
     * @param key
     * @param defaultValue
     * @return
     */
    public static int getInt(String key, int defaultValue) {
        String value = getString(key);
        return Integer.parseInt(value);
    }


    /**
     * 根据key获取值
     *
     * @param key
     * @return
     */
    public static boolean getBoolean(String key) {
        String value = env.getProperty(key);
        return new Boolean(value);
    }


    /**
     * 根据key获取值
     *
     * @param key
     * @param defaultValue
     * @return
     */
    public static boolean getBoolean(String key, boolean defaultValue) {
        String value = env.getProperty(key);
        if (StrUtil.isBlank(value)) {
            return defaultValue;
        }
        return new Boolean(value);
    }
}
